<template>
  <div class="tools-div">
    <!-- 搜索表单 -->
    <el-form label-width="40px" size="small">
      <el-row style="display: flex; align-items: center;height: 20px;">
        <el-button
          type="success"
          size="small"
          @click="addShow"
          class="add-button"
        >
          添 加
        </el-button>
        <el-form-item
          label="查询名称"
          style="flex-grow: 1;"
          class="search-item"
        >
          <el-input
            v-model="searchUnitName"
            style="width: 20%;"
            placeholder="规格名称"
          ></el-input>
          <el-button
            type="primary"
            size="small"
            @click="handleClick"
            style="margin-left: 5px;"
          >
            搜索
          </el-button>
          <el-button size="small" @click="handleClickReset">
            重置
          </el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </div>

  <el-table :data="list" style="width: 100%">
    <el-table-column prop="name" label="名称" />
    <el-table-column prop="createTime" label="创建时间" />
    <el-table-column label="操作" align="center" width="200" #default="scope">
      <el-button type="primary" size="small" @click="editShow(scope.row)">
        修改
      </el-button>
      <el-button type="danger" size="small" @click="remove(scope.row.id)">
        删除
      </el-button>
    </el-table-column>
  </el-table>
  <el-pagination
    v-model:current-page="pageParams.page"
    v-model:page-size="pageParams.limit"
    :page-sizes="[10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
  <el-dialog v-model="dialogVisible" title="添加或修改" width="40%">
    <el-form label-width="120px">
      <el-form-item label="名称">
        <el-input v-model="productUnit.name" />
      </el-form-item>
      <el-form-item align="right">
        <el-button type="primary" @click="saveOrUpdate">提交</el-button>
        <el-button @click="cancelEdit">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import {
  GetProductUnitPageList,
  UpdateProductUnit,
  Delete
} from "@/api/product/productunit.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { deepClone } from "@/utils/index.js";
import { debounce } from "@/utils";

// 数据列表
const list = ref([]);

// 分页条数据模型
const total = ref(0);

//分页条数据模型
const pageParamsForm = {
  page: 1, // 页码
  limit: 10 // 每页记录数
};
const pageParams = ref(pageParamsForm);

// 定义数据模型
const dialogVisible = ref(false);
//定义根据名称搜索
const searchUnitName = ref("");

// 添加表单数据模型
const defaultForm = {
  id: "",
  name: ""
};
const productUnit = ref(defaultForm);

//进入修改
const editShow = row => {
  const deepCopy = deepClone(row);
  productUnit.value = deepCopy;
  dialogVisible.value = true;
};

//进入添加
const addShow = () => {
  dialogVisible.value = true;
  productUnit.value = {
    id: "",
    name: ""
  };
};
//重置搜索内容
const resetData = () => {
  searchUnitName.value = "";
  fetchData();
};
// 防抖
const handleClick = debounce(() => {
  fetchData();
}, 500);

// 防抖
const handleClickReset = debounce(() => {
  resetData();
}, 500);


// 钩子函数
onMounted(() => {
  fetchData();
});

//页面变化
const handleSizeChange = size => {
  pageParams.value.limit = size;
  fetchData();
};
const handleCurrentChange = number => {
  pageParams.value.page = number;
  fetchData();
};

// 重置规格表单
const resetProductSpec = () => {
  fetchData();
};

// 取消编辑时恢复到原始数据
const cancelEdit = () => {
  resetProductSpec();
  dialogVisible.value = false;
};

// 分页查询
const fetchData = async () => {
  try {
    const { page, limit } = pageParams.value;

    let response;
    if (searchUnitName.value) {
      console.log(
        "Page:",
        page,
        "Limit:",
        limit,
        "Search:按条件查询",
        searchUnitName.value
      );
      // 按条件查询
      response = await GetProductUnitPageList(page, limit, searchUnitName.value);
    } else {
      console.log(
        "Page:",
        page,
        "Limit:",
        limit,
        "Search:查询全部",
        searchUnitName.value
      );
      // 查询全部
      response = await GetProductUnitPageList(page, limit);
    }
    console.log(response);
    list.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    console.error("Failed to fetch data:", error);
  }
};
// 提交表单
// 商品单位操作：有ID更新，无ID新增
const saveOrUpdate = async () => {
  try {
    if (!productUnit.value.id) {
      if (
        productUnit.value.name != null &&
        productUnit.value.name != "" &&
        productUnit.value.name != undefined
      ) {
        // 新增
        await UpdateProductUnit(productUnit.value);
        ElMessage.success("新增成功");
      } else {
        ElMessage.warning("新增失败,不能为空");
      }
    } else {
      if (
        productUnit.value.name != null &&
        productUnit.value.name != "" &&
        productUnit.value.name != undefined
      ) {
        // 更新
        await UpdateProductUnit(productUnit.value);
        ElMessage.success("更新成功");
      } else {
        ElMessage.warning("修改失败,不能为空");
      }
    }
    dialogVisible.value = false;
    fetchData();
  } catch (error) {
    ElMessage.error("操作失败,不能为空");
  }
};

//删除
const remove = async id => {
  ElMessageBox.confirm("此操作将删除该记录, 是否继续?", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      await Delete(id);
      ElMessage.success("删除成功");
      fetchData();
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
};
</script>

<style scoped>
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.div-atrr {
  padding: 5px 10px;
  margin: 0 10px;
  background-color: powderblue;
  border-radius: 10px;
  font-weight: bold;
}

.search-div {
  margin-left: 10px;
  padding: 1px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.add-button {
  margin-bottom: 20px;
  margin-left: 10px;
}

.search-item {
  margin-left: 10px;
  padding-right: 40px;
  width: 60px;
}

.tools-div >>> .el-form-item__label {
  width: 60px !important;
}
</style>
